const tool = require('../tools/tool')

module.exports = {
    async addMessage(userId, type, senderType, message, categoryId, paperId, questionId) {
        let id = await tool.dbf().insertInto('chat', {
            type,
            senderType,
            message,
            categoryId,
            paperId,
            questionId,
            userId
        })
        return await formatChatMessage((await tool.dbf().selectWithParams(`select * from chat where id = ?`, [id]))[0])
    },
    async getLatestChatMessage(userId) {
        let re = await tool.dbf().selectWithParams(`select * from chat where userId = ? order by createdAt desc limit 0,1`, [userId])
        re = re[0]
        return await formatChatMessage(re)
    },
    async getChatMessage(userId, finalId) {
        let re = []
        if (finalId === undefined) {
            re = await tool.dbf().selectWithParams(`select * from chat where userId = ? order by id desc limit 0,10`, [userId])
        } else {
            re = await tool.dbf().selectWithParams(`select * from chat where userId = ? and id < ? order by id desc limit 0,10`, [userId, finalId])
        }
        for (let i = 0; i < re.length; i++) {
            re[i] = await formatChatMessage(re[i])
        }
        return re.reverse()
    },
    async getUserChatRoom(userId) {
        let userInfo = await tool.methods.user().getSingleInfo.byId(userId)
        if (!userInfo) throw '用户不存在'
        let re = {
            ...await this.getStatus(userId),
            messages: await this.getChatMessage(userId),

        }
        return re
    },
    async getStatus(userId) {
        let userInfo = await tool.methods.user().getSingleInfo.byId(userId)
        if (!userInfo) throw '用户不存在'
        let lastUserExamCache = await tool.methods.exam().getLatestOneCache(userInfo.id)
        if (lastUserExamCache) {
            if (!lastUserExamCache.finished && new Date() >= new Date(new Date(lastUserExamCache.startAt).getTime() + lastUserExamCache.paperInfo.duration * 60 * 1000)) {
                let scores = await tool.methods.exam().computeScore(false, lastUserExamCache.id)
                let score = 0
                for (let i = 0; i < scores.length; i++) {
                    score += scores[i].score
                }
                score /= scores.length
                if (isNaN(score)) score = 0
                await tool.methods.exam().updateCache.score(lastUserExamCache.id, score)
                lastUserExamCache = await tool.methods.exam().getLatestOneCache(userInfo.id)
                await tool.methods.chat().addMessage(userId, 1, -1, `由于已过考试截止时间，已自动交卷，您的成绩为${score}分。`)
            }
        }
        let re = {
            // 0:没有考试缓存 1:正在进行考试 2:考试已结束成绩未达标或者强化已结束成绩仍未达标，但是需要进行强化训练 3:正在进行强化训练 4:有考试缓存，但是没有正在进行的考试和强化训练 -1:会员已过期
            status: await (async () => {
                if (userInfo.vip === false) return -1
                if (!lastUserExamCache) return 0
                let finished = (() => {
                    if (lastUserExamCache.reDoCaches.length) {
                        return lastUserExamCache.reDoCaches[0].finished
                    } else {
                        return lastUserExamCache.finished
                    }
                })()
                if (finished) {
                    let lastScore = (() => {
                        if (lastUserExamCache.reDoCaches.length) {
                            return lastUserExamCache.reDoCaches[0].score
                        } else {
                            return lastUserExamCache.score
                        }
                    })()
                    if (lastScore >= (await tool.methods.settings().getItem('passScore'))) {
                        return 4
                    }
                    return 2
                } else {
                    if (lastUserExamCache.reDoCaches.length) {
                        return 3
                    }
                    return 1
                }
            })(),
            // 上次考试成绩
            score: undefined,
            // 倒计时
            timer: undefined
        }
        re.score = await (async () => {
            if (re.status === 2 || re.status === 4) {
                return (() => {
                    if (lastUserExamCache.reDoCaches.length) {
                        return lastUserExamCache.reDoCaches[0].score
                    } else {
                        return lastUserExamCache.score
                    }
                })()
            }
            return undefined
        })()
        re.timer = await (async () => {
            if (re.status === 1) {
                return parseInt(((new Date((new Date(lastUserExamCache.startAt)).getTime() + lastUserExamCache.paperInfo.duration * 60 * 1000)).getTime() - (new Date()).getTime() - 10000) / 1000)
            }
            return undefined
        })()
        return re
    },
    async getLastChatMessages(userId, num = 5) {
        let re = await tool.dbf().selectWithParams(`select * from chat where userId = ? and senderType != 0 order by createdAt desc limit 0, ?`, [userId, num])
        for (let i = 0; i < re.length; i++) {
            re[i] = await formatChatMessage(re[i])
        }
        return re.reverse()
    },
    async changeMessageArrToString(messageArr) {
        let re = `最近${messageArr.length}条消息：
        `
        for (let i = 0; i < messageArr.length; i++) {
            if (messageArr[i].senderType === -1) re += `你向用户发送${messageArr[i].type === 1 ? '消息' : '问题'}：${await (async () => {
                if (messageArr[i].type === 1) return messageArr[i].message
                if (messageArr[i].type === 2) {
                    return await tool.methods.question().getQuestionString(messageArr[i].questionId)
                }
            })()}
            
            `
            if (messageArr[i].senderType === 1) re += `用户向你发送${messageArr[i].type === 1 ? '消息' : '问题'}：${await (async () => {
                if (messageArr[i].type === 1) return messageArr[i].message
                if (messageArr[i].type === 2) {
                    return await tool.methods.question().getQuestionString(messageArr[i].questionId)
                }
            })()}
            
            `
        }
        return re
    },
    async getChatHistoryString(userId) {
        let re = ''
        let res = await tool.dbf().selectWithParams(`select message, senderType from chat where userId = ?`, [userId])
        for (let i = 0; i < res.length; i++) {
            re += `${res[i].senderType === 1 ? '用户：' : 'AI：'}${res[i].message}`
        }
        return re
    }
}

async function formatChatMessage(item) {
    item.createdAt_read = tool.formatTimeNew(new Date(item.createdAt))
    item.updatedAt_read = tool.formatTimeNew(new Date(item.updatedAt))
    try {
        item.userAnswer = JSON.parse(item.userAnswer)
    } catch (error) {

    }
    if (item.type === 2) {
        item.questionInfo = await tool.methods.question().getSingle(item.questionId)
    }
    return item
}